package com.jy.app.lib.net;

import android.util.Base64;

import com.jy.app.lib.utils.LogUtil;
import com.jy.app.lib.utils.MD5Utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * app生成签名的工具
 * @author Administrator
 *
 */
public class AppSignUtil {

	private static int signPeriod = 30*60*1000;
//	/**
//	 * 验证签名
//	 * @param appId
//	 * @param timestamp
//	 * @param clientType
//	 * @param paramsMap
//	 * @param secretKey
//	 */
//	public static boolean verifySign(Integer appId, String timestamp, String clientType, Map<String,Object> paramsMap, String secretKey, String sign) throws RuntimeException{
//			if(timestamp == null || timestamp.equals("")){
// 				throw new RuntimeException("访问校验失败：时间戳不能为空！["+timestamp+"]");
// 			}
// 			long period = System.currentTimeMillis()-Long.parseLong(timestamp);
// 			if(signPeriod > period && period > -signPeriod){
// 				throw new RuntimeException("访问校验失败：时间戳已过期！["+timestamp+"]");
// 			}
//		    if(!sign.trim().equals(getSign(appId, timestamp, clientType, paramsMap, secretKey))){
//		    	throw new RuntimeException("访问校验失败：无效的签名！");
//		    }
//		    return true;
//	}

	/**
	 * 生成签名规则
	 * @param appId
	 * @param timestamp
	 * @param secretKey
	 * @return
	 */
	public static String getSign(Integer appId, String timestamp, String clientType, Map<String,Object> paramsMap,String secretKey){ 		
		StringBuffer sign = new StringBuffer();
 		sign.append(appId).append(":");
 		sign.append(timestamp.trim()).append(":");
 		sign.append(clientType.trim()).append(":");
		if(paramsMap != null && !paramsMap.isEmpty()){
			sign.append(handleParams(paramsMap).trim());
		}
 		sign.append(secretKey.trim()).append(":");
 		String s = Base64.encodeToString(MD5Utils.MD5(sign.toString()).getBytes(),Base64.NO_WRAP);
		if(HttpUtil.ENABLE_LOG){
 			LogUtil.i("params="+sign.toString());
 			LogUtil.i("sign="+s);
		}
 		return s;
 	}
	
	/**
	 * 对参数按字母的顺序进行排序，组合
	 * @param paramsMap
	 * @return
	 */
	private static String handleParams(Map<String,Object> paramsMap){
		List<String> keys = new ArrayList<String>();
		keys.addAll(paramsMap.keySet());
		Collections.sort(keys);
		StringBuffer sb = new StringBuffer("");
		for(String key : keys){
			sb.append(paramsMap.get(key)).append(":");
		}
		return sb.toString();
	}
}
